package com.bjesc_b2c.app.appraiset.mvp.view.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.bjesc_b2c.app.appraiset.R;
import com.bjesc_b2c.app.appraiset.base.BaseFragmentActivity;
import com.bjesc_b2c.app.appraiset.http.IApiActivityRequest;
import com.bjesc_b2c.app.appraiset.mvp.presenter.CusDetailsPresenter;
import com.bjesc_b2c.app.appraiset.mvp.presenter.impl.CusDetailsPresenterImpl;
import com.bjesc_b2c.app.appraiset.mvp.view.CusDetailsView;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.CustomerTrajectoryFragment;
import com.bjesc_b2c.app.appraiset.mvp.view.fragment.DemandCarFragment;
import com.bjesc_b2c.app.appraiset.utils.CustomSharedPreferences;
import com.bjesc_b2c.app.appraiset.widget.dialog.DateTimeDialog;
import com.bjesc_b2c.app.appraiset.widget.dialog.DealerDialog;
import com.bjesc_b2c.app.appraiset.widget.dialog.SelectTimeDialog;
import com.example.codeutils.utils.TimeUtils;
import com.orhanobut.logger.Logger;
import com.rxretrofit_build.util.MapUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import master_bean.CustomerDetailsBean;
import rxbus_base.RxBus;
import rxretrofit_base.model.KeyBean;
import rxretrofit_base.model.ShowType;
import rxretrofit_base.model.TokenBean;
import rxretrofit_base.net.BaseSubscriber;
import rxretrofit_base.net.RxRequest;

import static com.bjesc_b2c.app.appraiset.R.id.btn_operate;
import static com.bjesc_b2c.app.appraiset.R.id.rlty_order_info;
import static com.bjesc_b2c.app.appraiset.R.id.tv_add_time;
import static com.example.codeutils.utils.Utils.context;

/**
 * Created by yidong on 2017/5/24.
 */

public class CustomerDetailsActivity extends BaseFragmentActivity implements View.OnClickListener, CusDetailsView, DemandCarFragment.DealerDialogListener, DateTimeDialog.MyOnDateSetListener {

    @InjectView(R.id.line_1)
    View oneLineView;
    @InjectView(R.id.line_2)
    View twoLineView;
    @InjectView(R.id.tv_title)
    TextView title;
    @InjectView(R.id.tv_customer_track)
    TextView trackTv;
    @InjectView(R.id.tv_demand_car)
    TextView demandTv;
    @InjectView(R.id.tv_tourists_name)
    TextView touristsNameTv;
    @InjectView(R.id.tv_first_time)
    TextView firstTimeTv;
    @InjectView(R.id.tv_last_time)
    TextView lastTimeTv;
    @InjectView(tv_add_time)
    TextView nextTimeTv;
    @InjectView(R.id.tv_installment)
    TextView installmentTv;
    @InjectView(R.id.tv_client_order)
    TextView orderStatusTv;
    @InjectView(btn_operate)
    Button btnOperate;

    private List<View> views;
    private List<TextView> texts;
    private CusDetailsPresenter presenter;
    private String telNumber = "";
    private CustomerDetailsBean custData;
    private int buttonType = 1;
    private SelectTimeDialog timeDialog;
    private String dispatch_id;
    private SimpleDateFormat mFormatter = new SimpleDateFormat("yyyy-MM-dd hh:mm aa");

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_details);
        ButterKnife.inject(this);
        title.setText("订单详情");
        getLineList();
        changeViewColor(oneLineView);
        presenter = new CusDetailsPresenterImpl(this);
        dispatch_id = CustomSharedPreferences.getString(this, KeyBean.ORDER_ID.valueOf(), KeyBean.FILE_NAME.valueOf());
        presenter.getDetails(dispatch_id);
    }

    @Override
    protected void onResume() {
        super.onResume();


    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    private void getLineList() {
        views = new ArrayList<>();
        texts = new ArrayList<>();
        views.add(oneLineView);
        views.add(twoLineView);
        texts.add(trackTv);
        texts.add(demandTv);
    }

    @OnClick({R.id.rlty_order_info, R.id.tv_look_info, R.id.iv_return, R.id.iv_master_phone,
            R.id.tv_master_msg, R.id.tv_customer_track, R.id.tv_demand_car, R.id.btn_operate, R.id.btn_move_order})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_return:    //返回
                finish();
                break;
//            case tv_add_time:    //添加跟进时间
////                timeDialog = new SelectTimeDialog(CustomerDetailsActivity.this, timeListener, true);
//                DateTimeDialog dateTimeDialog = new DateTimeDialog(this, null, this);
//                dateTimeDialog.hideOrShow();
//                break;
            case rlty_order_info:
                Intent intento = new Intent(CustomerDetailsActivity.this, OrderInfoActivity.class);
                startActivityForResult(intento, 6);
                break;
            case R.id.btn_move_order:    //返回
                startIntent(new Intent(CustomerDetailsActivity.this, MoveOrderActivity.class), false);
                break;

            case R.id.tv_look_info:    //查看客户信息
                startIntent(new Intent(CustomerDetailsActivity.this, CustomerInfoActivity.class), false);
                break;
            case R.id.iv_master_phone: //打电话
                if (!TextUtils.isEmpty(telNumber)) {
                    call(telNumber);
                } else {
                    showToast("没有获取到电话号码");
                }
                break;
            case R.id.tv_master_msg: //发短信
                if (!TextUtils.isEmpty(telNumber)) {
                    sendto(telNumber);
                } else {
                    showToast("没有获取到电话号码");
                }
                break;
            case R.id.tv_customer_track: //客户轨迹
                changeViewColor(oneLineView);
                buttonType = 1;
                btnOperate.setText("添加跟进");
                switchContent(CustomerTrajectoryFragment.class, R.id.framen_customer_source);
                break;
            case R.id.tv_demand_car: //需求车辆
                changeViewColor(twoLineView);
                btnOperate.setText("添加需求车辆");
                buttonType = 2;
                Bundle args = new Bundle();
                args.putSerializable("DemandCar", custData.getDemand_car());
                switchContent(DemandCarFragment.class, R.id.framen_customer_source, args);
                RxBus.getInstance().sendData("DemandCar", custData.getDemand_car());
                break;
            case R.id.btn_operate: //
                if (buttonType == 1) {
                    startActivityForResult(new Intent(CustomerDetailsActivity.this, FollowActivity.class), 1);
                }
                if (buttonType == 2) {
                    startActivityForResult(new Intent(CustomerDetailsActivity.this, DemandCarActivity.class), 2);
                }
                break;

        }
    }

    @Override
    public void onDateSet(Date date) {
//        time.setText(mFormatter.format(date) + "");
        Logger.e("time===" + mFormatter.format(date) + "");
        long fftime = TimeUtils.date2Millis(date);
        Logger.e("time===" + fftime);
        HashMap<String, Object> build = new MapUtil()
                .put("dispatch_id", dispatch_id)
                .put("time", fftime)
                .build();
        RxRequest.request(ShowType.SHOW, RxRequest.getClient(context, build).create(IApiActivityRequest.class).addNextTime(),
                new BaseSubscriber<TokenBean>(context) {
                    @Override
                    public void onSuccess(TokenBean o) {
                        showToast(o.getMessage());
                    }

                    @Override
                    public void onFailure(Throwable e) {

                    }
                });
    }

    /**
     * 调用拨号功能
     *
     * @param phone 电话号码
     */
    private void call(String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startIntent(intent, false);
    }

    private void sendto(String phone) {
        Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:" + phone));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startIntent(intent, false);
    }

    @Override
    public void getDatas(CustomerDetailsBean data) {
        custData = data;
        telNumber = data.getTourists().getTel();
        touristsNameTv.setText(data.getTourists().getName());
        String frist = getResources().getString(R.string.first_time);
        String fristTime = String.format(frist, TimeUtils.millis2String(Long.valueOf(data.getTourists().getFirst_follow_time())));
        firstTimeTv.setText(fristTime);
        String last = getResources().getString(R.string.last_time);
        String lastTime = String.format(last, TimeUtils.millis2String(Long.valueOf(data.getTourists().getLast_follow_time())));
        lastTimeTv.setText(lastTime);
        String insta = getResources().getString(R.string.installment);

        if (!TextUtils.isEmpty(data.getDispatch().getStatus())) {
            String status = data.getDispatch().getStatus();
//    2博精成交 3战败 4未见面 5见面未成交
//            ： 1成功分配 2博精成交 3战败
            if (status.equals("2")) {
                orderStatusTv.setText("博精成交");
            }
            if (status.equals("3")) {
                orderStatusTv.setText("战败");
            }
            if (status.equals("1")) {
                orderStatusTv.setText("成功分配");
            }

        }

        if (data.getTourists().getInstallment().equals("1")) {
            installmentTv.setText(String.format(insta, "有"));
        } else {
            installmentTv.setText(String.format(insta, "无"));
        }
//        if (TextUtils.isEmpty(data.getTourists().getNext_follow_time())) {
//            nextTimeTv.setText("该客户没有下次跟进时间，点击添加");
//        } else {
//            String nextTime = getResources().getString(R.string.next_time);
//            nextTime = String.format(nextTime, TimeUtils.millis2String(Long.valueOf(data.getTourists().getNext_follow_time())));
//            nextTimeTv.setText(nextTime);
//        }
        CustomSharedPreferences.saveString(CustomerDetailsActivity.this, new MapUtil().put(KeyBean.CARID.valueOf(), data.getDemand_car().getCar_id()).build(), KeyBean.FILE_NAME.valueOf());
        Bundle args = new Bundle();
        args.putSerializable("FollowList", (ArrayList) data.getFollow_history());
        changeViewColor(oneLineView);
        switchContent(CustomerTrajectoryFragment.class, R.id.framen_customer_source, args);
        RxBus.getInstance().sendData("trajectory", data.getFollow_history());

    }

    //按钮选项
    public void changeViewColor(View v) {
        for (int i = 0; i < views.size(); i++) {
            if (v == views.get(i)) {
                views.get(i).setBackgroundResource(R.color.colorFFFF7900);
                texts.get(i).setTextColor(getResources().getColor(R.color.colorFFFF7900));
            } else {
                views.get(i).setBackgroundResource(R.color.colorLine);
                texts.get(i).setTextColor(getResources().getColor(R.color.colorFF030303));
            }
        }
    }

    @Override
    public void createDiaog() {
        DealerDialog dialog = new DealerDialog(CustomerDetailsActivity.this, custData.getDealer());
        dialog.show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == 11 || resultCode == 22) {
            presenter.getDetails(dispatch_id);
        }
    }
//    @Override
//    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        switch (resultCode){
//            case RequestAndResultCode.CountryVariousCityActivity_ResultCode_Area:
////                 data.getStringExtra("provinceId");
////                 data.getStringExtra("provinceName");
////                 data.getStringExtra("cityId");
//                cityName = data.getStringExtra("cityName");
//                license_city = data.getStringExtra("cityId");
//                cityTv.setText(cityName);
//                break;
//            case RequestAndResultCode.CarModelActivity_Result:
//                brandId = data.getStringExtra("brandId");
//                brandName = data.getStringExtra("brandName");
//                brandNameTv.setText(brandName);
//                break;
//            case RequestAndResultCode.CarSeriesActivity_Result:
//                carPriceTv.setText(data.getStringExtra("typeName"));
//                carPriceType = data.getStringExtra("typeId");
//                break;
//            case RequestAndResultCode.BIGCARSOURCEPHOTOACTIVITY_BACK_CARENGINEFRAGMENT_RESULT:
//                orderTypeTv.setText(data.getStringExtra("typeName"));
//                status = data.getStringExtra("typeId");
//                break;
//
//        }
//    }
}
